package com.jrx.anytxn.common.uitl;

import com.jrx.anytxn.common.constant.Constants;

import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;

/**
 * @program: anytxn-cf-common
 * @description: 流水号工具类
 * @author: xiaoyu.jing
 * @date: 2019-11-26 20:03
 **/
public class SeqUtils {

    /**
     * 格式：CLS+yyyyMMddHHmmssSSS+12位随机数,保证流水的唯一性
     *
     * @return
     */
    public static String getSN() {
        String channelCode = "CCS";
        return //渠道标识
                channelCode + getSNByLength(29)//随机码
                ;
    }


    private SeqUtils() {
    }

    /**
     * 获取指定长度的序列号
     * 日期 yyyyMMddHHmmssSSS占前17位
     *
     * @param seqLength 要生成的随机数长度
     * @return 随机序列号
     */
    public static String getSNByLength(int seqLength) {
        Date curr = new Date();
        StringBuilder sb = new StringBuilder();
        //yyyyMMddHHmmssSSS
        sb.append(DateUtils.format(curr, "yyyyMMddHHmmssSSS"));
        int suffixLength = seqLength - 17;
        if (suffixLength <= 0) {
            return sb.toString();
        }

        sb.append(getRandomNumber(suffixLength));//随机码

        return sb.toString();
    }


    public static String getRandomNumber(int seqLength) {
        String seqNo = "";
        SecureRandom r = null;
        try {
            // 获取高强度安全随机数生成器
            r = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            // 获取普通的安全随机数生成器
            r = new SecureRandom();
        }
        seqNo = seqNo + formatStr(new BigInteger(165, r).toString(10).toUpperCase().substring(0, seqLength),
                seqLength, true, "0");
        return seqNo;
    }

    private static String formatStr(String str, int length, boolean isBefore, String str1) {
        int l = length - str.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < l; i++) {
            sb.append(str1);
        }
        if (isBefore) {
            return sb.toString() + str;
        } else {
            return str + sb.toString();
        }
    }

    /**
     * 获取txnNumber
     *
     * @return txnNumber
     */
    public static String getTxnNumber() {
        //获取随机数
        String randomStr = SeqUtils.getSNByLength(29);
        return Constants.APP_ABBREVIATION + randomStr;
    }

    //生成联盟核心流水号
    public static String generateSeqNo(int seqInt) {
        String nextSeqNumber = Integer.toString(seqInt);
        StringBuffer appendStr = new StringBuffer();
        if (nextSeqNumber.length() < 6) {
            for (int i = 0; i < 6 - nextSeqNumber.length(); i++) {
                appendStr.append("0");
            }
        }
        nextSeqNumber = appendStr.append(nextSeqNumber).toString();
        return nextSeqNumber;
    }

}

